﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Tasks;

using Visifire.Charts;
using sil;
using ESRI.ArcGIS.Client.Symbols;
using System.Threading;
using System.Windows.Threading;

using System.Collections.ObjectModel;

using GisWeb.ServiceReference1;
using GisWeb;
namespace GisWeb
{
    public partial class MainPage : UserControl
    {

       //点击对比分析按钮
        private void btnclick(object sender, RoutedEventArgs e)
        {
            switch (mapclick)
            {
                case 0: //myMap.MouseClick += new EventHandler<Map.MouseEventArgs>(myMap_MouseClick);

                    // baseWindow.ParentLayoutRoot = paraFolder;
                    comBaseWindow.Show();
                    comBaseWindow.Closed += new EventHandler(comBaseWindow_Closed);
                    comBaseWindow.singleChoose += (object pa, EventArgs ea) => { MyDraw.DrawMode = DrawMode.Point; MyDraw.IsEnabled = true; };
                    comBaseWindow.multiChoose += (object pa, EventArgs ea) => { MyDraw.DrawMode = DrawMode.Rectangle; MyDraw.IsEnabled = true; };

                    // baseWindow.closeButton += new EventHandler(baseWindow_closeButton);
                    // baseWindow.Closed += baseWindow_closeButton;

                    mapclick = 2;
                    break;
                case 1: MessageBox.Show("正在运行基础查询模块，请先停止再进行查询"); break;
                case 2: MessageBox.Show("正在运行对比分析模块，请先停止再进行查询"); break;
                case 3: MessageBox.Show("正在运行经济指数预测模块，请先停止再进行查询"); break;
                case 4: MessageBox.Show("正在运行投资分析模块，请先停止再进行查询"); break;
                case 5: MessageBox.Show("正在运行重心转移模块，请先停止再进行查询"); break;

            }
        }
        
      



        //多区域查询后执行的操作
        private void QueryTask_ExecuteCompleted(object sender, ESRI.ArcGIS.Client.Tasks.QueryEventArgs args)
        {
            //查询后的结果存储在这里
            FeatureSet featureSet = args.FeatureSet;

            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }
            GraphicsLayer graphicsLayer = myMap.Layers["gra"] as GraphicsLayer;

            //查询的结果非空时
            if (featureSet != null && featureSet.Features.Count > 0)
            {
                foreach (Graphic feature in featureSet.Features)
                {
                    feature.Symbol = LayoutRoot.Resources["fill"] as SimpleFillSymbol;
                    // 

                    // if (cityGroup.Contains(feature)) { continue; }
                    // MessageBox.Show(cityGroup.Contains(feature).ToString());
                    //查询的区域的信息存储在cityGroup中

                    cityGroup.Add(feature);
                    int multi_select = 0;
                    for (int i = 0; i < cityGroup.Count - 1; i++)
                    {
                        if (cityGroup[i].Attributes["NAME"].ToString() == feature.Attributes["NAME"].ToString())
                        {
                            multi_select = 1;
                            cityGroup.RemoveAt(cityGroup.Count - 1);
                            break;
                        }
                    }
                    if (multi_select == 0)
                    {
                        graphicsLayer.Graphics.Insert(0, feature);
                        Query com_query = new Query();
                        com_query.Where = "CITYNAME like '%" + feature.Attributes["NAME"] + "%'";
                        com_query.OutFields.Add("*");
                        Query per_query = new Query();
                        per_query.Where = "CITYNAME like '%" + feature.Attributes["NAME"] + "%'";

                        QueryTask com_task = new QueryTask("http://arcgis:6080/arcgis/rest/services/HuNanMapService/MapServer/5");
                        QueryTask per_task = new QueryTask("http://arcgis:6080/arcgis/rest/services/HuNanMapService/MapServer/10");
                        QueryTask popu_task = new QueryTask("http://arcgis:6080/arcgis/rest/services/HuNanMapService/MapServer/12");
                        per_task.ExecuteCompleted += new EventHandler<QueryEventArgs>(per_task_ExecuteCompleted);
                        com_task.ExecuteCompleted += new EventHandler<QueryEventArgs>(com_task_ExecuteCompleted);
                        popu_task.ExecuteCompleted += new EventHandler<QueryEventArgs>(popu_task_ExecuteCompleted);
                        per_task.ExecuteAsync(com_query, feature.Attributes["NAME"].ToString());
                        com_task.ExecuteAsync(com_query, feature.Attributes["NAME"].ToString());

                        popu_task.ExecuteAsync(com_query, feature.Attributes["NAME"].ToString());
                    }
                }


                //for (int i = 0; i < cityGroup.Count; i++)
                //{
                //    MessageBox.Show(cityGroup[i].Attributes["NAME"].ToString());
                //}
                //ResultsDisplay.Visibility = Visibility.Visible;
            }
            //multiSelect.IsEnabled = false;
        }





        //画图完后执行的操作
        private void MyDraw_DrawComplete(object sender, ESRI.ArcGIS.Client.DrawEventArgs args)
        {
            QueryTask queryTask = new QueryTask("http://arcgis:6080/arcgis/rest/services/HuNanMapService/MapServer/3");


            //查询后执行的操作
            queryTask.ExecuteCompleted += QueryTask_ExecuteCompleted;

            //查询失败后执行的操作
            //queryTask.Failed += QueryTask_Failed;
            GraphicsLayer graphicsLayer = myMap.Layers["gra"] as GraphicsLayer;


            Query query = new ESRI.ArcGIS.Client.Tasks.Query();
            // Specify fields to return from query
            query.OutFields.Add("*");
            query.Geometry = args.Geometry;
            query.Where = "1=1";
            // Return geometry with result features
            query.ReturnGeometry = true;
            query.OutSpatialReference = myMap.SpatialReference;

            queryTask.ExecuteAsync(query);
        }


        //人口对比图生成
        void popu_task_ExecuteCompleted(object sender, QueryEventArgs e)
        {
            FeatureSet featureSet = e.FeatureSet;
            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }
            else
            {

                DataSeries dataseries = new DataSeries();

    
                // MessageBox.Show("人口");
                //  dataseries.LabelAngle = -30;

                foreach (Graphic graph in featureSet)
                {
                    DataPoint dp = new DataPoint();
                    dp.XValue = double.Parse(graph.Attributes["TIME"].ToString().Substring(0, 4));
                    dp.YValue = double.Parse(graph.Attributes["POPVALUE"].ToString()) / 10000;
                    dp.AxisXLabel = dp.XValue + "年";

                    dataseries.DataPoints.Add(dp);





                }

                DataSeries series = new DataSeries();
                // series.HorizontalAlignment = HorizontalAlignment.Right;
 
                series.Name = e.UserState.ToString();
                int chartType = 0;
                try { chartType = comResultWindow.combo.SelectedIndex; }
                catch (Exception ttt)
                {
                    Console.Write(ttt.Message);

                }
                switch (chartType)
                {
                    case 0: series.RenderAs = RenderAs.Line; break;
                    case 1: series.RenderAs = RenderAs.Column; break;
                    case 2: series.RenderAs = RenderAs.Bar; break;
                    case 3: series.RenderAs = RenderAs.StackedColumn; break;
                    case 4: series.RenderAs = RenderAs.StackedArea; break;



                }

                series.LegendText = e.UserState.ToString();
                //series.ShowInLegend = true;

                series.ToolTipText = "#AxisXLabel,#Series,#YValue";
                //排序
                foreach (DataPoint sortedPoint in dataseries.DataPoints.OrderBy(xaml => xaml.XValue))
                {
                    series.DataPoints.Add(sortedPoint);


                }
                // yaxis.ValueFormatString = "##";
                // yaxis.AxisLabels.Angle = -30;

                // popuCompare.AxesX.Add(yaxis);
                // MessageBox.Show("ok");
                popuCompare.AxesY.Clear();
                Axis yaxis = new Axis();
                yaxis.Suffix = "万人";
                popuCompare.AxesY.Add(yaxis);
                popuCompare.Series.Add(series);
               
                // MessageBox.Show("人口1");
                try
                {

                    comResultWindow.popu_com.Children.Add(popuCompare);
                    //   MessageBox.Show("人口3");
                }
                catch (Exception t) { Console.Write(t.Message); }

                //  MessageBox.Show("人口2");

            }
        }



        //人均gdp对比图生成
        void per_task_ExecuteCompleted(object sender, QueryEventArgs e)
        {
            FeatureSet featureSet = e.FeatureSet;
            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }
            else
            {

                DataSeries dataseries = new DataSeries();

                // dataseries.XValueFormatString = "####";


                //  dataseries.LabelAngle = -30;

                foreach (Graphic graph in featureSet)
                {
                    DataPoint dp = new DataPoint();
                    dp.XValue = double.Parse(graph.Attributes["TIME"].ToString().Substring(0, 4));
                    dp.YValue = double.Parse(graph.Attributes["PERGDPVALUE"].ToString()) / 1000;
                    dp.AxisXLabel = dp.XValue + "年";
               
                    dataseries.DataPoints.Add(dp);





                }
                DataSeries series = new DataSeries();
                int chartType = 0;
                try { chartType = comResultWindow.combo.SelectedIndex; }
                catch (Exception ttt)
                {
                    Console.Write(ttt.Message);

                }
                switch (chartType)
                {
                    case 0: series.RenderAs = RenderAs.Line; break;
                    case 1: series.RenderAs = RenderAs.Column; break;
                    case 2: series.RenderAs = RenderAs.Bar; break;
                    case 3: series.RenderAs = RenderAs.StackedColumn; break;
                    case 4: series.RenderAs = RenderAs.StackedArea; break;



                }
                series.Name = e.UserState.ToString();
                series.LegendText = e.UserState.ToString();
                series.ToolTipText = "#AxisXLabel,#Series,#YValue";
                foreach (DataPoint sortedPoint in dataseries.DataPoints.OrderBy(xaml => xaml.XValue))
                {
                    series.DataPoints.Add(sortedPoint);


                }
                // yaxis.ValueFormatString = "##";
                // yaxis.AxisLabels.Angle = -30;

                // comparechart.AxesX.Add(yaxis);
                //MessageBox.Show("ok");
                perCompare.AxesY.Clear();
                Axis yaxis = new Axis();
                yaxis.Suffix="千元";
                perCompare.AxesY.Add(yaxis);
                perCompare.Series.Add(series);
                try
                {
                    comResultWindow.per_com.Children.Add(perCompare);

                }
                catch (Exception t)
                {
                    Console.Write(t.Message);
                }



            }

        }


        //将查询完的结果装入GDP对比图中
        void com_task_ExecuteCompleted(object sender, QueryEventArgs e)
        {
            FeatureSet featureSet = e.FeatureSet;
            if (featureSet == null || featureSet.Features.Count < 1)
            {
                MessageBox.Show("No features returned from query");
                return;
            }
            else
            {

                DataSeries dataseries = new DataSeries();

                // dataseries.XValueFormatString = "####";


                //  dataseries.LabelAngle = -30;

                foreach (Graphic graph in featureSet)
                {
                    DataPoint dp = new DataPoint();
                    dp.XValue = double.Parse(graph.Attributes["TIME"].ToString().Substring(0, 4));
                    dp.YValue = double.Parse(graph.Attributes["GDPVALUE"].ToString()) / 10000000;
                    dp.AxisXLabel = dp.XValue + "年";

                    dataseries.DataPoints.Add(dp);





                }
                DataSeries series = new DataSeries();
                int chartType = 0;
                try { chartType = comResultWindow.combo.SelectedIndex; }
                catch (Exception ttt)
                {
                    Console.Write(ttt.Message);

                }
                switch (chartType)
                {
                    case 0: series.RenderAs = RenderAs.Line; break;
                    case 1: series.RenderAs = RenderAs.Column; break;
                    case 2: series.RenderAs = RenderAs.Bar; break;
                    case 3: series.RenderAs = RenderAs.StackedColumn; break;
                    case 4: series.RenderAs = RenderAs.StackedArea; break;



                }
                series.LegendText = e.UserState.ToString();
                foreach (DataPoint sortedPoint in dataseries.DataPoints.OrderBy(xaml => xaml.XValue))
                {
                    series.DataPoints.Add(sortedPoint);


                }
                // yaxis.ValueFormatString = "##";
                // yaxis.AxisLabels.Angle = -30;
                series.Name = e.UserState.ToString();
                comparechart.LightingEnabled = true;
                series.ToolTipText = "#AxisXLabel,#Series,#YValue";

                //  MessageBox.Show("ok");
                comparechart.AxesY.Clear();
                Axis yaxis = new Axis();
                yaxis.Suffix = "百万元";
                comparechart.AxesY.Add(yaxis);
                comparechart.Series.Add(series);
                try
                {
                    comResultWindow.gdp_com.Children.Add(comparechart);


                }
                catch (Exception t) { Console.Write(t.Message); }
                try { comResultWindow.Show(); comResultWindow.showCom = 1; }
                catch (Exception t) { Console.Write(t.Message); }



            }
        }

        //停止对比查询服务
        void comBaseWindow_Closed(object sender, EventArgs e)
        {
            comBaseWindow.single.IsChecked = false;
            comBaseWindow.multi.IsChecked = false;
            comBaseWindow.Close();
            gra.Graphics.Clear();
            cityGroup.RemoveRange(0, cityGroup.Count);
            comparechart.Series.Clear();
            perCompare.Series.Clear();
            popuCompare.Series.Clear();
            comResultWindow.Close();
            MyDraw.IsEnabled = false;
            mapclick = 0;
        }

    }
}